<template>
  <div class="login">
    <!-- 顶部导航条 -->
    <van-nav-bar
      title="登陆"
    />
    <van-form
    @failed='onFailed'
    @submit='onSubmit'
    >
    <!-- 表单区域 -->
    <van-cell-group>
      <van-field
      v-model.trim="user.mobile"
      type="tel"
      label="手机号"
      :rules="[{ pattern: /^1\d{10}$/, message: '请输入正确的手机号'}]"
      />
      <van-field
      v-model.trim="user.code"
      type="password"
      label="密码"
      :rules="[{ pattern: /^\d{6}$/, message: '请输入正确的密码'}]"
      />
    </van-cell-group>

    <!-- 按钮 -->
    <div class="btn-warp">
      <van-button type="info">登陆</van-button>
    </div>
    </van-form>
  </div>
</template>

<script>
import { login, getProfile } from '../../api/user.js'

console.log(login)

export default {
  data () {
    return {
      user: {
        mobile: '13912345678', // 初始帐号
        code: '246810' // 固定密码
      }
    }
  },
  methods: {
    onSubmit () {
      this.hLogin()
      console.log('验证成功')
    },
    onFailed () {
      console.log('验证失败')
    },
    async hLogin () {
      // login(mobile, code)
      try {
        // 1. 收集用户信息
        console.log(this.user)
        // 2. 表单验证

        this.$toast.loading({
          duration: 0, // 持续展示 toast,永远不会关闭，它会被后续的toast覆盖
          overlay: true, // 整体添加一个遮罩
          message: '加载中...'
        })
        // 3. 发请求
        const res = await login(this.user.mobile, this.user.code)
        console.log('res', res)
        // 关闭loading
        this.$toast.success('欢迎' + this.user.code)
        this.$store.commit('mSetTokenInfo', res.data.data)
        const userinfo = await getProfile()
        console.log(userinfo)
        this.$store.commit('userInfo/mSetUserInfo', userinfo.data.data)
        this.$router.push('/')
      } catch (err) {
        console.log(err)
        this.$toast.fail('登陆失败了')
      }
      // 4. 根据请求的返回结果，做后续的处理
    }
  }
}
</script>

<style lang="less" scoped>
  .login .btn-warp {
      padding: 20px;
      .van-button {
          width: 100%;
          background-color: #6db4fd;
          color:#fff;
      }
  }
</style>
